package schedule

import (
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/tpl"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"github.com/gorhill/cronexpr"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/go-log"
	"net/http"
	"time"
)

type CreateReq struct {
	Name     string `json:"name,omitempty"`
	Template string `json:"template,omitempty"`
	Cron     string `json:"cron,omitempty"`
	StartAt  string `json:"startAt,omitempty"`
}

func create(ctx server.Context) {
	var err error
	var req CreateReq
	var resp app.Response

	err = ctx.C.ReadJSON(&req)
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusInternalServerError
		ctx.Json(resp)
		return
	}
	// TODO check
	if len(req.Name) == 0 {
		resp.Code = http.StatusBadRequest
		ctx.Json(resp)
		return
	}
	_, err = tpl.GetTpl(req.Template)
	if err != nil {
		log.Info("template not found: %s", req.Template)
		log.Info(err)
		resp.Code = http.StatusBadRequest
		ctx.Json(resp)
		return
	}
	expr, err := cronexpr.Parse(req.Cron)
	if err != nil {
		log.Info("cron invalid")
		log.Info(err)
		resp.Code = http.StatusBadRequest
		resp.Message = "cron invalid"
		ctx.Json(resp)
		return
	}
	var startAt time.Time
	if len(req.StartAt) == 0 {
		startAt = expr.Next(time.Now())
	} else {
		startAt, err = time.Parse(time.DateOnly, req.StartAt)
		if err != nil {
			log.Info("start date format: %s", req.StartAt)
			log.Info(err)
			resp.Code = http.StatusInternalServerError
			ctx.Json(resp)
			return
		}
	}

	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		var tmp db.RtpSchedule
		tmp.Name = req.Name
		tmp.Cron = req.Cron
		tmp.Template = req.Template
		tmp.StartAt = startAt
		tmp.NextRun = startAt
		tmp.Status = 10
		_, e = tx.Context.Insert(&tmp)
		return
	})

	if err != nil {
		log.Info("create schedule failed")
		log.Info(err)
		resp.Code = http.StatusInternalServerError
		ctx.Json(resp)
		return
	}
	resp.Code = http.StatusOK
	ctx.Json(resp)
}
